<template>
	<el-row>
		<div>
			<ChangeLang style="padding-left: 90%"></ChangeLang>
		</div>
		<el-col :span="10" :offset="9">

			<!-- <el-tabs v-model="activeName" @tab-click="handleClick">-->
			<!--<el-tab-pane label="用户登录" name="first">-->
			<!--   <el-col >-->
			<el-form :model="dynamicValidateForm" :rules="rules" ref="dynamicValidateForm" style="line-height: 20px;width: 50%;">
				<img src="../assets/logo.png" class="logo" style="width: 50%;">
				<el-form-item prop="username" labelWidth="0px">
					<el-input v-model="dynamicValidateForm.username" :placeholder="$t('login.mail')" style="width: 100%;"></el-input>
				</el-form-item>

				<el-form-item prop="password" labelWidth="0px">
					<el-input type="password" v-model="dynamicValidateForm.password" :placeholder="$t('login.password')" style="width: 100%;"></el-input>
				</el-form-item>
				<!-- <div class="ft">
                 <el-checkbox label="记住账号"></el-checkbox>
                 <router-link to="/register">忘记密码</router-link>
                </div>-->

				<el-col :span="24" :offset="0">
					<el-checkbox v-model="dynamicValidateForm.checked" style="float: left" :label='$t("login.recordAccount")'></el-checkbox>
					<p class="el-checkbox__label" style="float: right;margin-top: auto;color: #606266; cursor: pointer" @click="forgetPassword('dynamicValidateForm')">{{$t("login.forgetPassword")}}</p>
				</el-col>

				<el-button type="primary" @click="submitForm('dynamicValidateForm')" style="width: 100%">{{$t("login.logIn")}}</el-button>
				<!-- <div class="ft">
                   <router-link to="/register">注册新账号</router-link>
                  </div>-->
				<!--<el-col :span="24" :offset="0">-->
				<!--<p class="register" @click="jumpRegister">{{$t("login.register")}}</p>-->
				<!--</el-col>-->
			</el-form>

			<!-- </el-col>-->
			<!-- </el-tab-pane>-->
			<!--<el-tab-pane label="用户注册" name="second">
              <Register></Register>
            </el-tab-pane>-->
			<!--</el-tabs>-->
		</el-col>
	</el-row>
</template>

<script>
	import Register from '@/components/Register.vue'
	import * as types from '../store/types'
	import api from '../axios'
	import ChangeLang from '@/components/changeLang.vue'

	export default {
		name: 'login',
		data: function() {
			return {
				dynamicValidateForm: {
					username: '',
					password: '',
					checked: false
				},
				/*  activeName: this.$store.state.activeName,*/
				// 输入校验
				rules: {
					username: [{
							required: true,
							message: this.$t('login.inputEmail'),
							trigger: 'blur'
						},
						{
							max: 50,
							message: this.$t('login.emailLength'),
							trigger: 'blur'
						},
						{
							type: 'email',
							message: this.$t('login.inputEmail'),
							trigger: 'blur'
						}
					],
					password: {
						required: true,
						message: this.$t('login.inputPassword'),
						trigger: 'blur'
					}
				},
				rules2: {
					password: {
						required: true,
						message: this.$t('login.inputPassword'),
						trigger: 'blur'
					}
				}
			}
		},
		components: {
			Register: Register,
			ChangeLang: ChangeLang,
		},
		mounted: function() {
			this.getCookie()
		},
		methods: {

			handleClick: function(tab, event) {},
			// 重置
			resetForm: function(formName) {
				this.$refs[formName].resetFields();
			},
			//设置cookie
			setCookie: function(c_name, c_pwd, exdays) {
				var exdate = new Date(); //获取时间
				exdate.setTime(exdate.getTime() + 24 * 60 * 60 * 1000 * exdays); //保存的天数
				//字符串拼接cookie
				window.document.cookie = "userName" + "=" + c_name + ";path=/;expires=" + exdate.toGMTString();
				window.document.cookie = "userPwd" + "=" + c_pwd + ";path=/;expires=" + exdate.toGMTString();
			},
			//读取cookie
			getCookie: function() {

				if (this.dynamicValidateForm.checked = true && document.cookie.length > 0) {
					var arr = document.cookie.split('; '); //这里显示的格式需要切割一下自己可输出看下
					for (var i = 0; i < arr.length; i++) {
						var arr2 = arr[i].split('='); //再次切割
						//判断查找相对应的值
						if (arr2[0] == 'userName') {
							this.dynamicValidateForm.username = arr2[1]; //保存到保存数据的地方
						} else if (arr2[0] == 'userPwd') {
							this.dynamicValidateForm.password = arr2[1];
						}
					}
				}
			},
			// 登录
			submitForm: function(formName) {
				//判断复选框是否被勾选 勾选则调用配置cookie方法
				if (this.dynamicValidateForm.checked) {
					//传入账号名，密码，和保存天数3个参数
					this.setCookie(this.dynamicValidateForm.username, this.dynamicValidateForm.password, 100000000);
				} else {
					this.setCookie("", "", -1);
				}
				this.rules.password = this.rules2.password;
				this.$refs[formName].validate((valid) => {
					if (valid) {
						let opt = this.dynamicValidateForm;

						//                        let formdata = new FormData();
						//                        formdata.append("grant_type", "password");
						//                        formdata.append("userName", opt.username);
						//                        formdata.append("password", this.$getMD5(opt.password));
						//                        formdata.append("client_id", "topvision");
						//                        formdata.append("client_secret", "!Topvision@021201802");
						var formData = {
							'userName': opt.username,
							'password': this.$getMD5(opt.password)
						};
						api.hPost("/api/auth/login", formData, (data) => {
							if (!data.success) {
								this.$message.error(data.msg);
							} else {
								this.$message({
									type: 'success',
									message: this.$t('login.loginSuccessful'),
								});
								this.$store.dispatch('UserLogin', {
									username: data.data.userName,
									id: data.data.id,
									companyName: data.data.companyName,
									companyId: data.data.companyId,
									realName: data.data.realName,
									mobilephoneNumber: data.data.mobilephoneNumber
								});

								// 查询所有字典,保存到缓存中
								api.hGet("/api/dict/findAll", {}, (resp) => {
									if (!!resp && resp.length > 0) {
										localStorage.setItem('dictList', JSON.stringify(resp));
									}
								});
								let redirect = decodeURIComponent(this.$route.query.redirect || '/home');
								console.log(redirect)
								if (data.data.id == -999) {
									this.$router.push({
										path: '/orderInfo'
									})
								} else {
									this.$router.push({
										path: '/home'
									})
								}

							}
						});

					} else {
						console.log('Error Submit!!');
						return false;
					}
				});
			},
			goLink: function() {
				this.$router.push('/register');
			},
			jumpRegister() {
				this.$router.push('/register');
			},
			forgetpassword: function() {
				this.$router.push('/forgetpassword');
			},
			//忘记密码
			forgetPassword: function(formName) {
				var name = this.dynamicValidateForm.username;
				this.$refs[formName].resetFields();
				this.dynamicValidateForm.username = name;
				this.rules.password = null;
				this.$refs[formName].validate((valid) => {
					if (valid) {
						let opt = this.dynamicValidateForm;
						this.$confirm(this.$t('login.initializePassword'), this.$t('standard.prompt'), {
							confirmButtonText: this.$t('standard.confirm'),
							cancelButtonText: this.$t('standard.cancel'),
							type: 'warning'
						}).then(() => {
							var formData = {
								'userName': opt.username
							};
							api.hPost('/api/register/initialPassword', formData, (response) => {
								if (response.success) {
									this.$message.success(response.msg);
									this.addFormVisible = false;
									this.query(1);
								} else {
									this.$message.error(response.msg);
								}
							});
						});
					} else {
						console.log('Error Submit!!');
						return false;
					}
				});
			}
		}
	}
</script>

<style scoped lang="scss">
	.el-input {
		width: 50%;
		border: 2px solid #000000;
		background-image: url("../assets/shenhe.png");

	}

	.el-form-item__error {
		position: relative;
	}

	.el-button {
		width: 50%;
		border: 2px solid #000000;
		line-height: 10px;
		font-size: 16px;
		font-weight: bold;
		letter-spacing: 20px;
	}

	.register {
		font-size: 14px;
		padding-left: 10px;
		line-height: 19px;

		color: #606266;
		cursor: pointer;
		float: right;
	}

	.logo {
		width: 25%;
		//margin-bottom: 20 px;
		margin: 0 auto;
		margin-top: 100px;
	}
</style>
